package com.example.demo.controller;

import com.example.demo.model.TorrentComment;
import com.example.demo.service.TorrentCommentService;
import com.example.demo.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/seed")
public class TorrentCommentController {
    private final TorrentCommentService commentService;

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    @Autowired
    public TorrentCommentController(TorrentCommentService commentService) {
        this.commentService = commentService;
    }

    @PostMapping("/comment/post")
    @PreAuthorize("hasRole('USER')")
    public Response<Map<String, Object>> postComment(
            @RequestBody Map<String, Object> data,
            @RequestHeader("Authorization") String token) {
        try {
            // 检查 Token 格式
            if (token == null || !token.startsWith("Bearer ")) {
                return Response.badRequest("无效的令牌格式");
            }

            Long seedId = Long.valueOf(data.get("seedId").toString());
            Long userId = Long.valueOf(data.get("userId").toString());
            String content = (String) data.get("content");

            if (seedId == null || userId == null || content == null || content.trim().isEmpty()) {
                return Response.badRequest("缺少必要参数");
            }

            TorrentComment comment = commentService.createComment(seedId, userId, content, token);
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("id", comment.getId());
            responseData.put("userId", comment.getUserId());
            responseData.put("username", comment.getUsername());
            responseData.put("avatar", comment.getAvatar() != null ? comment.getAvatar() : "");
            responseData.put("content", comment.getContent());
            responseData.put("timestamp", comment.getTimestamp().format(FORMATTER));
            return Response.success(responseData);
        } catch (IllegalArgumentException e) {
            return Response.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("发表评论失败", e);
            return Response.serverError("发表评论失败: " + e.getMessage());
        }
    }

    @GetMapping("/getcomments/{seedId}/{userId}")
    public ResponseEntity<List<TorrentComment>> getComments(
            @PathVariable("seedId") Long seedId,
            @PathVariable("userId") Long userId) {
        try {
            List<TorrentComment> comments = commentService.getComments(seedId, userId);
            return ResponseEntity.ok(comments);
        } catch (IllegalArgumentException e) {
            log.error("获取评论失败: {}", e.getMessage());
            return ResponseEntity.status(400).body(null);
        } catch (Exception e) {
            log.error("获取评论失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }


}